package ddd.ajava.chapter6.question3;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ComputeBlocks {
	private int dimension=0;
	
	public ComputeBlocks(int dimension){
		this.dimension=dimension;
	}
	
	public static void main(String[] args) {
		ComputeBlocks compute=new ComputeBlocks(900*900);
		compute.distributeThread(30*30);
	}
	
	public void distributeThread(int blockCount){
		if(blockCount<=0) {
			System.out.println("分隔块数错误！");
			return;
		}
		
		ConcurrentHashMap<ImageAnalyzeThread, Integer> conThread=new ConcurrentHashMap<ImageAnalyzeThread, Integer>();
		ExecutorService executeService=Executors.newSingleThreadExecutor();
		ThreadMonitor threadMonitor=new ThreadMonitor(conThread);
		
		long beginMills=System.currentTimeMillis();
		System.out.println("begin mills:"+beginMills);
		
		int threads=dimension/blockCount;
		for(int i=0;i<blockCount;i++){
			ImageAnalyzeThread imgThread=new ImageAnalyzeThread(threads);
			conThread.put(imgThread, threads);
			imgThread.start();
		}
//		threadMonitor=new ThreadMonitor(conThread);
		Future<Long> times=executeService.submit(threadMonitor);
		long totalMills=0;
		try {
			long endMills=times.get();
			totalMills = endMills-beginMills;
			System.out.println("end mills:"+endMills);
			executeService.shutdown();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("The image demision "+dimension+" pixel,divided into "+blockCount+" blocks"+" totally use "+totalMills+"ms");
	}
}
